//
//  WKUIDelegateNormal.swift
//  LXReuseTools
//
//  Created by yoctech on 2021/8/12.
//

import UIKit
import WebKit

public class WKUIDelegateNormal: NSObject {

}

extension WKUIDelegateNormal: WKUIDelegate {
    public func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
        
        let alertView = UIAlertController.init(title: nil, message: message, preferredStyle: .alert)
        let okAction = UIAlertAction.init(title: "确定", style: .default) { (_) in
            completionHandler()
        }
        alertView.addAction(okAction)
        UIApplication.shared.topViewController?.present(alertView, animated: true, completion: nil)
        
    }
    
    public func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
        let alertView = UIAlertController.init(title: nil, message: message, preferredStyle: .alert)
        let okAction = UIAlertAction.init(title: "确定", style: .default) { (_) in
            completionHandler(true)
        }
        alertView.addAction(okAction)
        let escAction = UIAlertAction.init(title: "取消", style: .cancel) { (_) in
            completionHandler(false)
        }
        alertView.addAction(escAction)
        UIApplication.shared.topViewController?.present(alertView, animated: true, completion: nil)

    }
    
    public func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) {
        let alertView = UIAlertController.init(title: nil, message: prompt, preferredStyle: .alert)
        alertView.addTextField { (tf) in
            tf.text = defaultText
        }
        let okAction = UIAlertAction.init(title: "确定", style: .default) { (_) in
            completionHandler(alertView.textFields?.first?.text ?? "")
        }
        alertView.addAction(okAction)
        let escAction = UIAlertAction.init(title: "取消", style: .cancel) { (_) in
        }
        alertView.addAction(escAction)
        UIApplication.shared.topViewController?.present(alertView, animated: true, completion: nil)
    }
}
